package com.ycz.sas.jgen.handler;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;

import com.ycz.sas.jgen.domain.DBConfig;
import com.ycz.sas.jgen.domain.ServerConfig;
import com.ycz.sas.jgen.util.Resource;


public class XMLParser{

	public static List<ServerConfig> getServerConfigs(){
		List<ServerConfig> configList = new ArrayList<ServerConfig>();

		Resource res = new Resource();
		String xmlpath = "/com/ycz/sas/jgen/serverconfig.xml";
		InputStream is = res.getResourceAsStream(xmlpath);
		BufferedReader br = new BufferedReader(new InputStreamReader(is));
		String xmlFile = res.getResource(xmlpath).getFile();

		SAXBuilder builder = new SAXBuilder();

		try {
			Document doc = builder.build(is);
			Element configs = doc.getRootElement();
			List list = configs.getChildren("config");
			for (int i = 0; i < list.size(); i++) {
				Element ele = (Element) list.get(i);
				ServerConfig cfg = new ServerConfig();
				cfg.setName(ele.getChildText("name"));
				cfg.setHost(ele.getChildText("host"));
				cfg.setPort(ele.getChildText("port"));
				cfg.setUser(ele.getChildText("user"));
				cfg.setPassword(ele.getChildText("password"));
				cfg.setEashome(ele.getChildText("eashome"));

				configList.add(cfg);
			}

		} catch (JDOMException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return configList;
	}
	
	public static List<DBConfig> getDBConfigs(){
		List<DBConfig> configList = new ArrayList<DBConfig>();

		Resource res = new Resource();
		String xmlpath = "/com/ycz/sas/jgen/dbconfig.xml";
		InputStream is = res.getResourceAsStream(xmlpath);
		BufferedReader br = new BufferedReader(new InputStreamReader(is));
		String xmlFile = res.getResource(xmlpath).getFile();

		SAXBuilder builder = new SAXBuilder();

		try {
			Document doc = builder.build(is);
			Element configs = doc.getRootElement();
			List list = configs.getChildren("config");
			for (int i = 0; i < list.size(); i++) {
				Element ele = (Element) list.get(i);
				DBConfig cfg = new DBConfig();
				cfg.setKey(ele.getChildText("key"));
				cfg.setHost(ele.getChildText("host"));
				cfg.setPort(ele.getChildText("port"));
				cfg.setUser(ele.getChildText("user"));
				cfg.setPassword(ele.getChildText("password"));
				cfg.setDatabase(ele.getChildText("database"));

				configList.add(cfg);
			}

		} catch (JDOMException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return configList;
	}

}
